import { Button } from 'antd'
import { OrderedSet } from 'immutable'
import { ImportantEditModal } from '@/desktop/components'
import BuearyTabs from '@/desktop/components/BeautyTabs'
import Loading from '@/desktop/components/Loading'
import { type MomentContact } from '@/services/features/send-moment'
import { ByTags } from './by-tags'
import { useCache, useInitialData, useChoosed, useChoosedCount } from './logics'
import { ManualChoose } from './manual'
import './index.module.less'

export function ChooseContacts(props: {
  wxids: string[] // 当前要发送朋友圈的企业微信列表（根据这个确定哪些客户可以纳入范围）
  choosing: MomentContact[] | null // 为 null 代表未开启选择
  onChoosed: (scope: MomentContact[]) => void
}) {
  const { wxids, choosing, onChoosed } = props
  return <ImportantEditModal
    title="选择可见客户"
    open={!!choosing}
    onCancel={() => onChoosed(choosing!)}
    width="800px"
  >
    {choosing ? <Content wxids={wxids} choosed={choosing} onChoosed={onChoosed} /> : null}
  </ImportantEditModal>
}

const emptySet = OrderedSet<string>()

function Content(props: {
  wxids: string[]
  choosed: MomentContact[]
  onChoosed: (choosed: MomentContact[]) => void
}) {
  const { wxids: rawConfigWxids, choosed: rawInputChoosed, onChoosed } = props

  const cache = useCache()
  const { configQywxs, inputChoosed } = useInitialData(rawConfigWxids, rawInputChoosed, cache)
  const { choosed, setChoosed, choose, clear, formatChoosed } = useChoosed(cache, inputChoosed)
  const count = useChoosedCount(choosed)

  function save() {
    if (choosed) onChoosed(formatChoosed(choosed))
  }

  /**
   * ====================
   * 界面内容
   * ====================
   */
  const [currentTab, setCurrentTab] = useState<'tag' | 'manual'>('tag')

  if (!configQywxs || !choosed) {
    return <Loading />
  }

  return <>
    <main styleName="main">
      <BuearyTabs
        activeKey={currentTab}
        onChange={key => setCurrentTab(key as typeof currentTab)}
        items={[
          {
            label: '按标签选择' + (count.byTags ? `(${count.byTags})` : ''),
            key: 'tag',
            children: <ByTags
              cache={cache}
              configQywxs={configQywxs}
              choosed={choosed}
              choose={choose}
              setChoosed={setChoosed}
            />,
          },
          {
            label: '手动搜索' + (count.byManual ? `(${count.byManual})` : ''),
            key: 'manual',
            children: <ManualChoose
              cache={cache}
              configQywxs={configQywxs}
              choosed={choosed.get(null) ?? emptySet}
              choose={choose}
            />,
          },
        ]}
      />
    </main>

    <footer styleName="footer">
      {count.total ? (
        <div styleName="sum">
          <span>共选中 {count.total} 人</span>
          <a onClick={clear}>清空</a>
        </div>
      ) : (
        <div styleName="sum"></div>
      )}

      <Button type="primary" onClick={save}>
        确定
      </Button>
    </footer>
  </>
}
